/**
 * synchronized关键字
 * 锁对象。synchronized(this)和synchronized方法都是锁当前对象。
 */
package concurrent.t01;

import java.util.concurrent.TimeUnit;

public class Test_01 {

    private int count = 0;
    private Object o = new Object();

    // 锁定临界对象--多线程都能访问到的对象
    public void testSync1() {
        synchronized (o) {
            System.out.println(Thread.currentThread().getName()
                    + " count = " + count++);

            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 锁定当前对象--this
    public void testSync2() {
        synchronized (this) {
            System.out.println(Thread.currentThread().getName()
                    + " count = " + count++);

            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    // 同步方法锁定的是当前对象---this
    public synchronized void testSync3() {
        System.out.println(Thread.currentThread().getName()
                + " count = " + count++);
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        final Test_01 t = new Test_01();

        new Thread(new Runnable() {
            @Override
            public void run() {
                t.testSync1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                t.testSync3();
            }
        }).start();

    }

}
